/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: PerpetualContractTradeFragmentPresenter.java
 *   @Date: 19-6-17 下午3:41
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.presenter;

import android.os.Bundle;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.LinkedBlockingQueue;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.trade.bean.BookListBean;
import io.bhex.app.trade.sort.BookListSort;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.BookView;
import io.bhex.app.view.bean.Book;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.data_manager.NetWorkApiManager;
import io.bhex.sdk.enums.ORDER_ENTRUST_TYPE;
import io.bhex.sdk.enums.ORDER_TYPE;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.DepthDataBean;
import io.bhex.sdk.quote.bean.DepthSocketResponse;
import io.bhex.sdk.quote.bean.RiskLimitBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.bean.FuturesAssetListResponse;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfig;
import io.bhex.sdk.trade.bean.FuturesCreateOrderConfigResponse;
import io.bhex.sdk.trade.bean.FuturesFundingRatesResponse;
import io.bhex.sdk.trade.futures.FuturesApi;
import io.bhex.sdk.trade.futures.bean.EntrustOrderResponse;
import io.bhex.sdk.trade.futures.bean.FuturesOrderResponse;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrder;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrderResponse;
import io.bhex.sdk.trade.futures.bean.OrderCreateParams;
import io.bhex.sdk.trade.futures.bean.TradableBean;
import io.bhex.sdk.trade.futures.bean.TradableBeanResponse;

/**
 * 永续合约交易 Presenter
 */
public class PerpetualContractTradeFragmentPresenter extends BaseFragmentPresenter<PerpetualContractTradeFragmentPresenter.PerpetualContractTradeFragmentUI> {
    private BookDataHandleTask bookDataHandleTask;
    //盘口数据队列
    private LinkedBlockingQueue<DepthDataBean> depthDataQueue = new LinkedBlockingQueue<>();
    private boolean isResub;

    public void getUserInfo() {
        LoginApi.GetUserInfo(new SimpleResponseListener<UserInfoBean>(){
            @Override
            public void onSuccess(UserInfoBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    UserInfo.saveUserInfo(response);
                    getUI().showCheckOpenFutures();
                }
            }
        });
    }

    public interface PerpetualContractTradeFragmentUI extends AppUI {

        void showOpenOrders(List<FuturesOrderResponse> datas);

        void showHoldOrders(List<FuturesPositionOrder> datas);

        String getExchangeId();

        String getSymbols();

        String getQuoteToken();

        String getBaseToken();

        void showLatestPrice(TickerBean data);

//        void showDepthView(DepthDataBean data);

        /**
         * 更新交易界面资产信息
         *
         * @param token
         * @param asset
         */
        void updateAssettByToken(String token, String asset);

        void resetView();

        String getDigitStr();

        void createOrderSuccess();

        boolean isSelected();

        void showPlanningOrders(List<FuturesOrderResponse> mCurrentPlanningOrders);

        void showFundingRates(FuturesFundingRatesResponse response);

        void showTradableInfo(TradableBean tradableBean);

        void showCheckOpenFutures();

        void updateLevers();

        CoinPairBean getCurrentCoinInfoBean();

        int getDigitBase();

        boolean isCurrentAskOrderPrice(String priceStr);

        void updateBookList();

        boolean isCurrentBidOrderPrice(String priceStr);

        List<BookListBean> getBookListData();

        boolean isShowCumulativeVolume();
    }

    private static final String LOGTAG = "PerpetualContractTradeFragmentPresenter";
    //当前Fragment是否可见
    protected boolean isVisible;
    //默认普通委托列表
    private int currentShowEntrustOrderListType = ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType();
    protected List<FuturesOrderResponse> currentOrders = new ArrayList<>();
    private List<FuturesOrderResponse> mCurrentPlanningOrders = new ArrayList<>();
    protected List<FuturesPositionOrder> holdOrders = new ArrayList<>();

    protected DepthDataBean currentDepthData;
    protected String mPageId = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DebugLog.e(LOGTAG, "ON onCreate");
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, PerpetualContractTradeFragmentUI ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onResume() {
        super.onResume();
//        getCurrentOrdinaryEntrustOrders();
        sourceMapA.clear();
        sourceMapB.clear();
//        getUI().resetView();

        getCurrentOrdinaryEntrustOrders();
        subCurrentEntrustOrder();

        getCurrentPlanningOrders();

        getHoldOrders();
        subPositionOrder(getUI().getSymbols());
        getOrderSetting(getUI().getCurrentCoinInfoBean());

        if (getUI().isSelected() && isVisible) {
            getTicker();
            requestDepthData();
        }
    }

   /* @Override
    public void onPause() {
        super.onPause();
        //QuoteApi.UnSubTickers();
        //QuoteApi.UnSubDepthData();
    }*/

    private void unregisterEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * 取消所有event事件
     */
    private void cancelAllEvent() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        isVisible = visible;
        DebugLog.e("XXXXX", this.toString() + "  " + isVisible + "  isSelected " + getUI().isSelected());
        if (getUI().isSelected()) {
            if (isVisible) {
                getTicker();
                startBookTask();
                requestDepthData();
//            registerEventBus();
            }else{
                stopTask();
//            unregisterEventBus();
                QuoteApi.UnSubTickers();
                QuoteApi.UnSubDepthData();
            }
        }
        if (isVisible && getUI().isSelected()) {
//            getTicker();
//            requestDepthData();

            //刷新资产信息
            getAssetList(getUI().getQuoteToken());
            getAsset(getUI().getQuoteToken());
            subTradableInfo(getUI().getQuoteToken());
            getTradableInfo(getUI().getQuoteToken());
        }else{
//            //QuoteApi.UnSubTickers();
//            //QuoteApi.UnSubDepthData();
        }
//        DebugLog.e(LOGTAG, "ON onVisibleChanged " + visible);
    }


    /**
     * 刷新
     */
    public void refresh() {

        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        } else {
            if (!NetWorkStatus.isConnected(getActivity())) {
                ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
                return;
            }
            getAssetList(getUI().getQuoteToken());
            getAsset(getUI().getQuoteToken());
            subTradableInfo(getUI().getSymbols());
            getTradableInfo(getUI().getSymbols());
            getSettleStatus();
            refreshCurrentOrders();
            getHoldOrders();
        }
    }

    /**
     * 加载更多
     */
    public void loadMore() {
//        getHoldOrders(true);
    }

    /**
     * 刷新当前委托 http
     */
    public void refreshCurrentOrders() {
        if (!NetWorkApiManager.getTradeInstance().isOpen()) {
            getCurrentOrdinaryEntrustOrders();
        }
        //TODO 此处因为计划委托没有推送，临时方式刷新接口
        getCurrentPlanningOrders();
    }

    /**
     * 切换到当前接口
     * @param currentOrderTabSelectItem
     */
    public void switchCurrentOrderList(int currentOrderTabSelectItem) {
        switchOrderList(currentOrderTabSelectItem);
    }


    /**
     * 获取开仓最大杠杆数
     *
     * @param symbolId
     * @param currentSide
     * @return
     */
    public String getMaxLimitLever(String symbolId, String currentSide) {
        String maxLimit = "";
        RiskLimitBean riskLimitBean = riskLimitMap.get(symbolId + currentSide);
        if (riskLimitBean != null) {
            String initialMargin = riskLimitBean.getInitialMargin();
            if (!TextUtils.isEmpty(initialMargin)) {
                maxLimit = io.bhex.baselib.utils.NumberUtils.roundFormatDown(io.bhex.baselib.utils.NumberUtils.div(initialMargin, "1"), 2);
                if (!TextUtils.isEmpty(maxLimit) && maxLimit.endsWith(".00")) {
                    maxLimit = maxLimit.substring(0,maxLimit.indexOf(".00"));
                }
            }
        }
        return maxLimit;
    }

    /**
     * 获取最新价
     */
    public void getTicker() {

        QuoteApi.SubTicker(getUI().getExchangeId(), getUI().getSymbols(), new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI().isAlive() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        String s = data.getS();
                        if (!TextUtils.isEmpty(s)) {
                            if (s.equals(getUI().getSymbols())) {
                                getUI().showLatestPrice(data);
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });
    }

    /**
     * 获取盘口深度
     */
    public void requestDepthData() {
        if (!isVisible) {
            return;
        }
        clearDataQueue();
        isResub = true;
        QuoteApi.SubDepthData(getUI().getExchangeId(), getUI().getSymbols(), new NetWorkObserver<DepthSocketResponse>() {
            @Override
            public void onShowUI(DepthSocketResponse response) {
                if (getUI() == null || !getUI().isAlive() || response == null)
                    return;

                if (response.data != null && response.data.size() > 0)
                    if (response.data.get(0) != null) {
                        boolean bFirst = true;
                        if (response.f != null){
                            bFirst = response.f;
                        }
                        if (isResub) {
                            if (!bFirst) {
                                //重新发起了订阅，如果非首次推送到达的全量数据(有可能是推送到达延迟的旧数据)，直接丢弃非全量垃圾数据
                                return;
                            }else{
                                clearDataQueue();
                                isResub = false;
                            }
                        }

                        DepthDataBean depthData = response.data.get(0);
//                        depthData.setId(depthDataId++);
                        if (!TextUtils.isEmpty(response.symbol)) {
                            depthData.setS(response.symbol);
                        }
                        currentDepthData = depthData;

                        handleAndShowDepth(depthData, bFirst);
                    }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    /**
     * 重置所有订单（当前，历史订单）数据
     *
     * @param coinPairBeanParam
     */
    public void resetAllData(CoinPairBean coinPairBeanParam) {
//        cancelAllEvent();
        clearDataQueue();
        getUI().resetView();
        riskLimitMap.clear();
        orderConfigMap.clear();

        if (currentOrders != null) {
            currentOrders.clear();
            getUI().showOpenOrders(currentOrders);
        }
        if (mCurrentPlanningOrders != null) {
            mCurrentPlanningOrders.clear();
            getUI().showPlanningOrders(mCurrentPlanningOrders);
        }

        if (holdOrders != null) {
            holdOrders.clear();
            getUI().showHoldOrders(holdOrders);
        }

        getCurrentOrdinaryEntrustOrders();
        subCurrentEntrustOrder();

        getCurrentPlanningOrders();

        getHoldOrders();
        subPositionOrder(getUI().getSymbols());

        getAssetList(getUI().getQuoteToken());
        getTradableInfo(coinPairBeanParam.getSymbolId());
        subTradableInfo(getUI().getQuoteToken());

        //QuoteApi.UnSubTickers();
        //QuoteApi.UnSubDepthData();

        getTicker();
        requestDepthData();

        getOrderSetting(coinPairBeanParam);
        getSettleStatus();

    }

    /**
     * 改变盘口数量显示模式
     * @param isShowCumulativeVolume 是否以累计数量模式 >>> 显示盘口
     */
    public void changeBookQuantityShowMode(boolean isShowCumulativeVolume) {
        reSubDepth();
    }

    /**
     * 合并book列表小数
     *
     * @param digitDepth
     */
    public void changeMergeDigit(String digitDepth) {
        reSubDepth();
//        if (currentDepthData != null) {
//            handleAndShowDepth(currentDepthData, false);
//        }
    }

    /**
     * 处理并展示深度数据
     *
     * @param depthDataBean
     */
    private void handleAndShowDepth(DepthDataBean depthDataBean, boolean f) {
        if (TextUtils.isEmpty(depthDataBean.getS()) || getUI() == null || !getUI().isAlive() || depthDataBean == null || TextUtils.isEmpty(getUI().getSymbols())){
            return;
        }

        depthDataBean.f = f;
        if (!isVisible || !depthDataBean.getS().equals(getUI().getSymbols())) {
            return;
        }
//        EventBus.getDefault().post(depthDataBean);

        //添加盘口数据到待处理任务队列
        addDataQueue(depthDataBean);

    }

    /**
     * 添加盘口数据对象到待处理任务队列
     * @param depthDataBean
     */
    private void addDataQueue(DepthDataBean depthDataBean) {
        //添加盘口数据对象到队列
        try {
            if (!bookDataHandleTask.isAlive()) {
                if (getUI().isSelected() && isVisible) {
                    startBookTask();
                }
//                DebugLog.e("diff-task","task is not alive");
            }
            if (depthDataQueue.size()>AppData.TICKER.DEPTH_MAX_QUEUE_WATING_COUNT) {
                reSubDepth();
            }else{
//                DebugLog.e("Depth-COUNT", "QUEUE add data " + depthDataBean.getId() + "  " + depthDataBean.getS());
                depthDataQueue.put(depthDataBean);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重新订阅深度数据
     */
    private void reSubDepth() {
        clearDataQueue();
        requestDepthData();
    }

    /**
     * 清理队列数据
     */
    private void clearDataQueue() {
        if (depthDataQueue != null) {
            depthDataQueue.clear();
        }
    }

    /**
     * 开启队列处理数据
     */
    private void startBookTask() {
        bookDataHandleTask = new BookDataHandleTask();
        bookDataHandleTask.start();

    }

    private void stopTask(){
        if (bookDataHandleTask != null) {
            if (!bookDataHandleTask.isInterrupted()) {
                bookDataHandleTask.interrupt();
            }
        }
//        if (displayTask != null) {
//            if (!displayTask.isInterrupted()) {
//                displayTask.interrupt();
//            }
//        }
    }

    //book默认条数
    private static final int BOOK_LIST_DEFAULT_NUM = 10;

    private class BookDataHandleTask extends Thread{

        @Override
        public void run() {
            //循环队列，取出头部元素
            while (isVisible){
                excuteQueueTask();
            }

        }
    }


    private void excuteQueueTask() {
//        DebugLog.e("Depth-COUNT-Contract-diff", "QUEUE wating size >>>   " + depthDataQueue.size() + "  thread "+ Thread.currentThread().getId() + "  "+Thread.currentThread().getName());
        if (!depthDataQueue.isEmpty()) {
//                    DepthDataBean headerData = depthDataQueue.element();
            DepthDataBean headerData = depthDataQueue.poll(); //移除并返问队列头部的元素    如果队列为空，则返回null
            if (headerData != null) {
//                DebugLog.e("Depth-COUNT", "QUEUE handle start " + headerData.getId() + "  " + headerData.getS());
                List<List<String>> ask;
                List<List<String>> bit;


                if (headerData.getA() == null) {
                    ask = new ArrayList<>();
                } else {
                    ask = headerData.getA();
                }

                if (headerData.getB() == null) {
                    bit = new ArrayList<>();
                } else {
                    bit = headerData.getB();
                }

                headerData.setA(ask);
                headerData.setB(bit);

                //排序压缩合并后的全量数据
                if (headerData.f == true) {
                    sourceMapA.clear();
                    sourceMapB.clear();
                }

                List<List<String>> a = headerData.getA();
                for (List<String> result : a) {
                    float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
                    if (value > 0) {
                        sourceMapA.put(result.get(0), result.get(1));
                    } else {
                        sourceMapA.remove(result.get(0));
                    }
                }

                List<List<String>> b = headerData.getB();
                for (List<String> result : b) {
                    float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
                    if (value > 0) {
                        sourceMapB.put(result.get(0), result.get(1));
                    } else {
                        sourceMapB.remove(result.get(0));
                    }

                }

                //数据小数位合并
                String digitStr = getUI().getDigitStr();
                int digitCount = NumberUtils.calNumerCount(getActivity(), digitStr);

                Map<String, String> newMapA = new TreeMap<>(new BookListSort());
                for (String key : sourceMapA.keySet()) {
                    String newKey = "";
                    newKey = NumberUtils.roundUpString(key, digitCount);
                    float value = Float.valueOf(sourceMapA.get(key));
                    String s = newMapA.get(newKey);
                    s = TextUtils.isEmpty(s) ? "0" : s;
                    float newValue = Float.valueOf(s) + value;//累计量
                    newMapA.put(newKey, newValue + "");
                }

                Map<String, String> newMapB = new TreeMap<>(new BookListSort());
                for (String key : sourceMapB.keySet()) {
                    String newKey = NumberUtils.roundDownString(key, digitCount);
                    float value = Float.valueOf(sourceMapB.get(key));
                    String s = newMapB.get(newKey);
                    s = TextUtils.isEmpty(s) ? "0" : s;
                    float newValue = Float.valueOf(s) + value;//累计量
                    newMapB.put(newKey, newValue + "");
                }

                List<List<String>> A = new ArrayList<>();
                for (String key : newMapA.keySet()) {
                    ArrayList<String> item = new ArrayList<>();
                    item.add(key);
                    item.add(newMapA.get(key));
                    A.add(item);
                }
                headerData.setA(A);

                List<List<String>> B = new ArrayList<>();
                for (String key : newMapB.keySet()) {
                    ArrayList<String> item = new ArrayList<>();
                    item.add(key);
                    item.add(newMapB.get(key));
                    B.add(item);
                }
                headerData.setB(B);


                List<Book> bidBooks = new ArrayList<>();
                List<Book> askBooks = new ArrayList<>();

                /********/

                //阴影比例计算公式：成交金额/[展示买平均值+展示卖平均值）/2]%
                //截取显示档位所需数据-ask
                List<List<String>> resultA;
                if (A.size() > BOOK_LIST_DEFAULT_NUM) {
                    resultA = A.subList(0, BOOK_LIST_DEFAULT_NUM);
                } else {
                    resultA = A;
                }

                float totalADeal = 0;
                for (List<String> item : resultA) {
                    String priceStr = item.get(0);
                    String amountStr = item.get(1);

                    Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
                    Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

                    // totalADeal += price * amount;
                    totalADeal += amount;

                }

                float aV = resultA.size() > 0 ? totalADeal / resultA.size() : 0;
                // DebugLog.e("PROGress","TA "+aV +"  "+totalADeal);

                //截取显示档位所需数据-bid
                List<List<String>> resultB;
                if (B.size() > BOOK_LIST_DEFAULT_NUM) {
                    resultB = B.subList(B.size() - BOOK_LIST_DEFAULT_NUM, B.size());
                } else {
                    resultB = B;
                }

                float totalBDeal = 0;
                for (int i = resultB.size() - 1; i >= 0; i--) {
                    List<String> item = resultB.get(i);
                    String priceStr = item.get(0);
                    String amountStr = item.get(1);

                    // Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
                    Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

                    // totalBDeal += price * amount;
                    totalBDeal += amount;

                }
                float bV = resultB.size() > 0 ? totalBDeal / resultB.size() : 0;
                // DebugLog.w("PROGress","TB "+bV +"  "+totalBDeal);

                float average = (aV + bV) / (aV == 0 || bV == 0 ? 1 : 2);
                // DebugLog.w("PROGress","P=== "+average+"  "+aV +"   "+bV);
                float denominator = NumberUtils.sub(totalADeal, totalBDeal) > 0 ? totalADeal : totalBDeal;

                float currentTotalAmountOfA = 0;    //当前数量累积量
                for (List<String> item : resultA) {
                    String priceStr = item.get(0);
                    String amountStr = item.get(1);
//                    Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
                    Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

                    Book book1 = new Book();
                    book1.setBid(false);
                    book1.setPrice(priceStr);
                    book1.setPriceColor(getResources().getColor(R.color.red));
                    book1.setVolume(io.bhex.baselib.utils.NumberUtils.handVolumeLength(amountStr, getUI().getDigitBase()));
                    book1.setProgressColor(getResources().getColor(R.color.red20));
                    currentTotalAmountOfA += amount;
                    // float progress = price * amount / average;
                    float progress = currentTotalAmountOfA / denominator;
                    book1.setCumulativeVolume(io.bhex.baselib.utils.NumberUtils.handVolumeLength(new BigDecimal(currentTotalAmountOfA).toPlainString(), getUI().getDigitBase()));
                    // DebugLog.w("PROGress","A "+progress);
                    book1.setProgress(progress);
                    book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
                    book1.setHasOrderMarked(getUI().isCurrentAskOrderPrice(priceStr));
                    book1.setShowCumulativeVolume(getUI().isShowCumulativeVolume());
                    askBooks.add(book1);
                }

                //倒序一下
                if (BOOK_LIST_DEFAULT_NUM > askBooks.size()) {
                    int size = askBooks.size();
                    for (int i = 0; i < BOOK_LIST_DEFAULT_NUM - size; i++) {
                        Book book1 = new Book();
                        book1.setBid(false);
                        book1.setPrice("--");
                        book1.setPriceColor(getResources().getColor(R.color.red));
                        book1.setVolume("--");
                        book1.setCumulativeVolume("--");
                        book1.setProgressColor(getResources().getColor(R.color.red20));
                        book1.setProgress(0f);
                        book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
                        book1.setHasOrderMarked(false);
                        book1.setShowCumulativeVolume(getUI().isShowCumulativeVolume());
                        askBooks.add(book1);
                    }
                }

                float currentTotalAmountOfB = 0;    //当前数量累积量
                for (int i = resultB.size() - 1; i >= 0; i--) {
                    List<String> item = resultB.get(i);
                    String priceStr = item.get(0);
                    String amountStr = item.get(1);
                    Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
                    Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

                    Book book1 = new Book();
                    book1.setBid(true);
                    book1.setPrice(priceStr);
                    book1.setPriceColor(getResources().getColor(R.color.green));
                    book1.setVolume(io.bhex.baselib.utils.NumberUtils.handVolumeLength(amountStr, getUI().getDigitBase()));
                    book1.setProgressColor(getResources().getColor(R.color.green20));
                    //            float progress = price * amount / average;
                    currentTotalAmountOfB += amount;
                    book1.setCumulativeVolume(io.bhex.baselib.utils.NumberUtils.handVolumeLength(new BigDecimal(currentTotalAmountOfB).toPlainString(), getUI().getDigitBase()));
                    float progress = currentTotalAmountOfB / denominator;
                    //            DebugLog.w("PROGress","B "+progress);
                    book1.setProgress(progress);
                    book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
                    book1.setHasOrderMarked(getUI().isCurrentBidOrderPrice(priceStr));
                    book1.setShowCumulativeVolume(getUI().isShowCumulativeVolume());
                    bidBooks.add(book1);
                }

                //        for (List<String> item : resultB) {
                //            String priceStr = item.get(0);
                //            String amountStr = item.get(1);
                //            Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
                //            Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);
                //
                //            Book book1 = new Book();
                //            book1.setBid(true);
                //            book1.setPrice(priceStr);
                //            book1.setPriceColor(getResources().getColor(R.color.green));
                //            book1.setVolume(io.bhex.baselib.utils.NumberUtils.handVolumeLength(amountStr,digitBase));
                //            book1.setProgressColor(getResources().getColor(R.color.green20));
                //            float progress = price * amount / average;
                ////            DebugLog.w("PROGress","B "+progress);
                //            book1.setProgress(progress);
                //            book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
                //            bidBooks.add(book1);
                //        }
                //        //倒序一下
                //        Collections.reverse(bidBooks);
                if (BOOK_LIST_DEFAULT_NUM > bidBooks.size()) {
                    int size = bidBooks.size();
                    for (int i = 0; i < BOOK_LIST_DEFAULT_NUM - size; i++) {
                        Book book1 = new Book();
                        book1.setBid(true);
                        book1.setPrice("--");
                        book1.setPriceColor(getResources().getColor(R.color.green));
                        book1.setVolume("--");
                        book1.setCumulativeVolume("--");
                        book1.setProgressColor(getResources().getColor(R.color.green20));
                        book1.setProgress(0f);
                        book1.setProgressMode(BookView.PROGRESS_RIGHT_MODE);
                        book1.setHasOrderMarked(false);
                        book1.setShowCumulativeVolume(getUI().isShowCumulativeVolume());
                        bidBooks.add(book1);
                    }
                }

                String askPrice1 = askBooks.get(0).getPrice();
                String bidPrice1 = bidBooks.get(0).getPrice();

//                DebugLog.e("Depth-COUNT", "QUEUE handle end   " + headerData.getId() + "  " + headerData.getS());

                if (askBooks.size()>0 && bidBooks.size() >0 && askPrice1.equals("--") && bidPrice1.equals("--") && NumberUtils.sub(bidPrice1, askPrice1) >= 0) {
                    //异常价格盘口
//                    DebugLog.e("Depth-COUNT", "socket QUEUE handle price exception >>>>> " + headerData.getId() + "  ask1 = " + askPrice1 + "  bid1 = " + bidPrice1);
//                    ToastUtils.showShort("price exception >>>>> " + headerData.getId() + "  ask1 = " + askPrice1 + "  bid1 = " + bidPrice1);
//                    LogToFile.e("DEPTH-DATA-EXCEPTION-ASK-ALL", Convert.formatJson(sourceMapA));
//                    LogToFile.e("DEPTH-DATA-EXCEPTION-BID-ALL", Convert.formatJson(sourceMapB));
//                    LogToFile.e("DEPTH-DATA-EXCEPTION-ASK", Convert.formatJson(askBooks));
//                    LogToFile.e("DEPTH-DATA-EXCEPTION-BID", Convert.formatJson(bidBooks));
                    getActivity().runOnUiThread(() -> {
                        reSubDepth();
                    });
                } else {
                    List<BookListBean> bookListData = getUI().getBookListData();
                    for (int askIndex = BOOK_LIST_DEFAULT_NUM; askIndex > 0; askIndex--) {
                        BookListBean bookListBean = bookListData.get(askIndex - 1);
                        bookListBean.setBook(askBooks.get(BOOK_LIST_DEFAULT_NUM - askIndex));
                    }

                    for (int bidIndex = BOOK_LIST_DEFAULT_NUM + 1; bidIndex < BOOK_LIST_DEFAULT_NUM * 2 + 1; bidIndex++) {
                        BookListBean bookListBean = bookListData.get(bidIndex);
                        bookListBean.setBook(bidBooks.get(bidIndex - BOOK_LIST_DEFAULT_NUM - 1));
                    }

                    //币对相同才会更新盘口
                    if (headerData.getS().equals(getUI().getSymbols())) {
//                        DebugLog.e("Depth-COUNT", "Depth update " + headerData.getId() + "  " + headerData.getS());
                        getUI().updateBookList();

                    }
                }

            }
        }
    }

    Map<String, String> sourceMapA = new TreeMap<>(new BookListSort());
    Map<String, String> sourceMapB = new TreeMap<>(new BookListSort());


    public DepthDataBean mergeData(DepthDataBean data) {
        List<List<String>> a = data.getA();
        List<List<String>> b = data.getB();
        String aMax = "0";
        String aMin = "0";
        if (a != null && a.size() > 0) {
            if (a.size()>100) {
                a = a.subList(0,100);
                data.setA(a);
            }
            aMax = a.get(a.size() - 1).get(0);
            aMin = a.get(0).get(0);
        }
        float aMinF = new BigDecimal(aMin).floatValue();
        float dValueOfA = new BigDecimal(aMax).subtract(new BigDecimal(aMin)).floatValue();
        String bMax = "0";
        String bMin = "0";
        if (b != null && b.size() > 0) {
            int bSize = b.size();
            if (bSize>100) {
                b = b.subList(bSize-100,bSize);
                data.setB(b);
            }
            bMax = b.get(b.size() - 1).get(0);
            bMin = b.get(0).get(0);
        }
        float bMaxF = new BigDecimal(bMax).floatValue();
        float dValueOfB = new BigDecimal(bMax).subtract(new BigDecimal(bMin)).floatValue();
        if (dValueOfA > dValueOfB && b.size() > 1) {
            //A 多
            for (int i = a.size() - 1; i >= 0; i--) {
                String priceStr = a.get(i).get(0);
                float price = new BigDecimal(priceStr).floatValue();
                if (price > aMinF + dValueOfB) {
                    a.remove(i);
                }
            }

            //判断是否需要补一根数据
            String priceStr = a.get(a.size() - 1).get(0);
            float price = new BigDecimal(priceStr).floatValue();
            if (price != aMinF + dValueOfB) {
                List<String> aLast = new ArrayList<>();
                aLast.add(String.valueOf(aMinF + dValueOfB));
                aLast.add("0");
                a.add(aLast);
            }

        } else if (dValueOfA < dValueOfB && a.size() > 1) {
            //B 多
            for (int i = b.size() - 1; i >= 0; i--) {
                String priceStr = b.get(i).get(0);
                float price = new BigDecimal(priceStr).floatValue();
                if (price < bMaxF - dValueOfA) {
                    b.remove(i);
                }
            }

            //判断是否需要补一根数据
            String priceStr = b.get(0).get(0);
            float price = new BigDecimal(priceStr).floatValue();
            if (price != aMinF + dValueOfB) {
                List<String> bLast = new ArrayList<>();
                bLast.add(String.valueOf(bMaxF - dValueOfA));
                bLast.add("0");
                b.add(0, bLast);
            }

        }
        return data;

    }

    /**
     * 切换订单列表
     *
     * @param orderListType
     */
    public void switchOrderList(int orderListType) {
        currentShowEntrustOrderListType = orderListType;
        if (getUI() != null) {
            if (orderListType == ORDER_TYPE.ORDER_TYPE_GENERAL_ENTRUSTMENT.getOrderType()) {
                getUI().showOpenOrders(currentOrders);
            } else if (orderListType == ORDER_TYPE.ORDER_TYPE_PLANNING_ENTRUSTMENT.getOrderType()) {
                getUI().showPlanningOrders(mCurrentPlanningOrders);
            } else if (orderListType == ORDER_TYPE.ORDER_TYPE_HOLD.getOrderType()) {
                getUI().showHoldOrders(holdOrders);
            }

        }
    }

    /**
     * 获取普通委托
     */
    public void getCurrentOrdinaryEntrustOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        FuturesApi.RequestOpenOrder(getUI().getSymbols(), "", "", 100, "", ORDER_ENTRUST_TYPE.LIMIT.getEntrustType(), new SimpleResponseListener<EntrustOrderResponse>() {

            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    currentOrders = response.getArray();
                    if (currentOrders != null) {
                        getUI().showOpenOrders(currentOrders);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }

    /**
     * 获取计划委托
     */
    public void getCurrentPlanningOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        FuturesApi.RequestOpenOrder(getUI().getSymbols(), "", "", 100, "", ORDER_ENTRUST_TYPE.STOP.getEntrustType(), new SimpleResponseListener<EntrustOrderResponse>() {

            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    mCurrentPlanningOrders = response.getArray();
                    if (mCurrentPlanningOrders != null) {
                        getUI().showPlanningOrders(mCurrentPlanningOrders);
                    }

                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 持仓订单
     *
     */
    public void getHoldOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        FuturesApi.RequestHoldOrders(getUI().getSymbols(), getUI().getExchangeId(), "", "", AppData.Config.PAGE_LIMIT, "", new SimpleResponseListener<FuturesPositionOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(FuturesPositionOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesPositionOrder> data = response.getArray();
                    if (data != null) {
                        holdOrders.clear();
                        holdOrders = data;
                        getUI().showHoldOrders(holdOrders);
                    }

                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }


    /**
     * 订阅当前-普通委托订单
     */
    protected synchronized void subCurrentEntrustOrder() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        FuturesApi.SubFuturesSymbolOrderChange(getUI().getSymbols(), new SimpleResponseListener<EntrustOrderResponse>() {
            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesOrderResponse> srcList = response.getArray();
                    boolean isOrderChange = false;
                    boolean isPlanOrderChange = false;
                    if (srcList != null && srcList.size() > 0) {
                        for (int i = srcList.size() - 1; i >= 0; i--) {
                            FuturesOrderResponse srcBean = srcList.get(i);

                            if (srcBean.getType().equals(ORDER_ENTRUST_TYPE.LIMIT.getEntrustType())) {
                                /** 普通委托单 ***********/

                                boolean hasSrcBean = false;
                                for (int j = 0; j < currentOrders.size(); j++) {
                                    if (srcBean.getOrderId().equalsIgnoreCase(currentOrders.get(j).getOrderId())) {
                                        isOrderChange = true;
                                        currentOrders.remove(j);
                                        //订单状态 (NEW 订单已创建 PARTIALLY_FILLED 部分成交FILLED 完全成交 CANCELED 已取消 REJECTED 已拒绝)
                                        if (getUI().getSymbols().equals(srcBean.getSymbolId()) && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED") && !srcBean.getStatus().equalsIgnoreCase("FILLED") && !srcBean.getStatus().equalsIgnoreCase("REJECTED"))
                                            currentOrders.add(j, srcBean);
                                        hasSrcBean = true;
                                        break;
                                    }
                                }
                                if (getUI().getSymbols().equals(srcBean.getSymbolId()) && hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED") && !srcBean.getStatus().equalsIgnoreCase("FILLED") && !srcBean.getStatus().equalsIgnoreCase("REJECTED"))
                                    currentOrders.add(0, srcBean);
                                isOrderChange = true;

                            } else {
                                /** 计划委托 ***********/
                                boolean hasSrcBean = false;
                                for (int j = 0; j < mCurrentPlanningOrders.size(); j++) {
                                    if (srcBean.getOrderId().equalsIgnoreCase(mCurrentPlanningOrders.get(j).getOrderId())) {
                                        isOrderChange = true;
                                        mCurrentPlanningOrders.remove(j);
                                        if (getUI().getSymbols().equals(srcBean.getSymbolId()) && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED") && !srcBean.getStatus().equalsIgnoreCase("FILLED") && !srcBean.getStatus().equalsIgnoreCase("REJECTED"))
                                            mCurrentPlanningOrders.add(j, srcBean);
                                        hasSrcBean = true;
                                        break;
                                    }
                                }
                                if (getUI().getSymbols().equals(srcBean.getSymbolId()) && hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED") && !srcBean.getStatus().equalsIgnoreCase("FILLED") && !srcBean.getStatus().equalsIgnoreCase("REJECTED"))
                                    mCurrentPlanningOrders.add(0, srcBean);
                                isPlanOrderChange = true;

                            }

                        }

                        if (currentOrders != null && isOrderChange) {
                            getUI().showOpenOrders(currentOrders);
                        }

                        if (mCurrentPlanningOrders != null && isPlanOrderChange) {
                            getUI().showPlanningOrders(mCurrentPlanningOrders);
                        }
                    }


                }
            }
        });

    }

    /**
     * 订阅持仓单
     *
     * @param symbols
     */
    private void subPositionOrder(final String symbols) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        FuturesApi.SubFuturesHoldOrderChange(symbols, new SimpleResponseListener<FuturesPositionOrderResponse>() {
            @Override
            public void onSuccess(FuturesPositionOrderResponse response) {
                super.onSuccess(response);
                try {
                    if (CodeUtils.isSuccess(response, true)) {
                        if (!response.getReqSymbolId().equals(getUI().getSymbols())) {  //此处因为该方法被多次调用了 导致了多次多种symbolId的数据监听，而且socket没有取消监听的办法导致，所以只能临时加过滤
                            return;
                        }
                        List<FuturesPositionOrder> list = new ArrayList<>();
                        for (int i = 0; i < response.getArray().size(); i++) {
                            FuturesPositionOrder orderBean = response.getArray().get(i);
                            if (orderBean != null && orderBean.getSymbolId().equalsIgnoreCase(getUI().getSymbols())) {
                                list.add(orderBean);
                            }
                        }
                        holdOrders = list;

                        getUI().showHoldOrders(holdOrders);

                    }
                } catch (Exception e) {
                }
            }
        });

    }


    /**
     * 获取资产列表
     *
     * @param token
     */
    protected synchronized void getAssetList(final String token) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        if (token.equalsIgnoreCase(getUI().getQuoteToken())) {
            FuturesApi.SubFutureTokenBalanceChange(token, new SimpleResponseListener<FuturesAssetListResponse.FuturesAssetBean>() {

                @Override
                public void onSuccess(FuturesAssetListResponse.FuturesAssetBean response) {
                    super.onSuccess(response);
                    if (getUI() == null || !getUI().isAlive() || response == null)
                        return;
                    if (response != null) {
                        getUI().updateAssettByToken(token, response.availableMargin);
                    } else {
                        //因为API接口返回的资产列表，如果没有资产，则没有改币种资产信息，所以为空，代表没有查询到余额 默认按零资产处理
                        getUI().updateAssettByToken(token, "0");
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }
    }


    /**
     * 获取资产
     *
     * @param tokenId
     */
    protected void getAsset(final String tokenId) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        if (tokenId.equalsIgnoreCase(getUI().getQuoteToken())) {
            AssetApi.RequestFuturesTokenIdAsset(tokenId, new SimpleResponseListener<FuturesAssetListResponse>() {
                @Override
                public void onFinish() {
                    super.onFinish();
                }

                @Override
                public void onSuccess(FuturesAssetListResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, true)) {
                        List<FuturesAssetListResponse.FuturesAssetBean> data = response.array;
                        if (data != null) {
                            if (data.size() > 0) {
                                FuturesAssetListResponse.FuturesAssetBean assetBean = data.get(0);
                                if (assetBean != null) {
                                    getUI().updateAssettByToken(tokenId, assetBean.availableMargin);
                                }
                            }
                        }
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }

    }

    /**
     * 下单
     *
     * @param exchangeId
     * @param clientOrderId
     * @param symbolId
     * @param side
     * @param type
     * @param price
     * @param priceType
     * @param triggerPrice
     * @param quantity
     * @param leverage
     */
    public void createOrder(String exchangeId, String clientOrderId, String symbolId, String side, String type, String price, String priceType, String triggerPrice, String quantity, String leverage) {

        OrderCreateParams orderCreateParams = new OrderCreateParams();
        orderCreateParams.exchangeId = exchangeId;
        orderCreateParams.clientOrderId = clientOrderId;
        orderCreateParams.symbolId = symbolId;
        orderCreateParams.side = side;
        orderCreateParams.type = type;
        orderCreateParams.price = price;
        orderCreateParams.priceType = priceType;
        orderCreateParams.triggerPrice = triggerPrice;
        orderCreateParams.quantity = quantity;
        orderCreateParams.leverage = leverage;


        FuturesApi.orderCreate(orderCreateParams, new SimpleResponseListener<FuturesOrderResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("", "");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(FuturesOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    ToastUtils.showShort(getActivity(), getString(R.string.string_create_order_success));
                    getUI().createOrderSuccess();
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_create_order_failed));
            }
        });
    }

    public void cancelOrder(FuturesOrderResponse orderItem) {
        FuturesApi.orderCancel(System.currentTimeMillis() + "", orderItem.getOrderId(), orderItem.getType(), new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("", "");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
//                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_success));
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
            }
        });
    }

    private HashMap<String, FuturesCreateOrderConfig> orderConfigMap = new HashMap<String, FuturesCreateOrderConfig>();
    private HashMap<String, RiskLimitBean> riskLimitMap = new HashMap<String, RiskLimitBean>();

    /**
     * 下单配置项（费率，下单设置，风险限额）
     */
    public void getOrderSetting(CoinPairBean coinPairBean) {
        if (!UserInfo.isLogin()) {
            return;
        }
        if (coinPairBean == null || !UserInfo.isLogin()) {
            return;
        }
        String exchangeId = coinPairBean.getExchangeId();
        String symbolId = coinPairBean.getSymbolId();
        FuturesApi.getFuturesCreateOrderConfig(exchangeId, symbolId, new SimpleResponseListener<FuturesCreateOrderConfigResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(FuturesCreateOrderConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    List<FuturesCreateOrderConfig> orderConfigs = response.getArray();
                    if (orderConfigs != null && orderConfigs.size() > 0) {
//                        for (FuturesCreateOrderConfig orderConfig : orderConfigs) {
//                            if (orderConfig != null) {
//                                //保存下单配置实体数据
//                                orderConfigMap.put(orderConfig.getSymbolId(),orderConfig);
//                            }
//                        }
                        FuturesCreateOrderConfig futuresCreateOrderConfig = orderConfigs.get(0);
                        if (futuresCreateOrderConfig != null) {
                            //保存下单配置实体数据
                            orderConfigMap.put(futuresCreateOrderConfig.getSymbolId(), futuresCreateOrderConfig);
                            List<RiskLimitBean> riskLimit = futuresCreateOrderConfig.getRiskLimit();
                            if (riskLimit != null) {
                                for (RiskLimitBean riskLimitBean : riskLimit) {
                                    //保存下单配置-风险限额实体数据
                                    riskLimitMap.put(futuresCreateOrderConfig.getSymbolId() + riskLimitBean.getSide(), riskLimitBean);
                                }
                                getUI().updateLevers();
                            }
                        }
                    }

                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取结算时间、资金费率
     */
    public void getSettleStatus() {
        FuturesApi.getFundingRates(new SimpleResponseListener<FuturesFundingRatesResponse>() {
            @Override
            public void onSuccess(FuturesFundingRatesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    getUI().showFundingRates(response);
                }
            }
        });

    }

    /**
     * 期货可交易信息
     * @param symbolId
     */
    public synchronized void getTradableInfo(final String symbolId){
        if (!UserInfo.isLogin()) {
            return;
        }
        AssetApi.getAssetTradable(symbolId ,new SimpleResponseListener<TradableBeanResponse>(){
            @Override
            public void onSuccess(TradableBeanResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    if (getUI() == null || !getUI().isAlive() || response == null)
                        return;
                    List<TradableBean> data = response.getArray();
                    if (data.size()>0) {
                        TradableBean tradableBean = data.get(0);
                        if (tradableBean.getTokenId().equals(symbolId)) {
                            getUI().showTradableInfo(tradableBean);
                        }
                    }
                }
            }
        });
    }

    /**
     * 期货可交易信息 包括仓位、可平信息  socket + http
     * @param symbolId
     *
     */
    public synchronized void subTradableInfo(final String symbolId){
        if (!UserInfo.isLogin()) {
            return;
        }
        FuturesApi.SubFutureTradableInfo(symbolId,new SimpleResponseListener<TradableBean>(){
            @Override
            public void onSuccess(TradableBean response) {
                super.onSuccess(response);
                if (getUI() == null || !getUI().isAlive() || response == null){
                    return;
                }
                if (response != null) {
                    getUI().showTradableInfo(response);
                }
            }
        });
    }
}
